package com.xrj4j.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.xrj4j.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.xrj4j.common.ResultCode.*;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseResult BusinessExceptionHandler(BusinessException ex) {
        if (ex.getCode() != -1) {
            log.error("code: {},msg: {}", ex.getCode(), ex.getMessage(), ex);
        }
        if (StringUtils.isBlank(ex.getLocalizedMessage()) || StringUtils.isBlank(ex.getMessage())) {
            return ResponseResult.error(ERROR.getCode(), ERROR.getDesc());
        }
        return ResponseResult.error(ex.getCode(), ex.getMessage());
    }

    /**
     * Assert业务异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseResult AssertExceptionHandler(IllegalArgumentException ex) {
        log.error(" msg : {}", ex.getMessage(), ex);
        if (StringUtils.isBlank(ex.getLocalizedMessage())) {
            return ResponseResult.error(ERROR.getCode(), ERROR.getDesc());
        }
        return ResponseResult.error(ex.getMessage());
    }

    /**
     * 登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public ResponseResult NotLoginExceptionHandler(NotLoginException ex) {
        log.error(" msg : {}", ex.getMessage(), ex);
        return ResponseResult.error(NOT_LOGIN.getCode(), NOT_LOGIN.getDesc());
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public ResponseResult NotPermissionExceptionHandler(NotPermissionException ex) {
        log.error(" msg : {}", ex.getMessage(), ex);
        return ResponseResult.error(NO_PERMISSION.getCode(), "无此权限：" + ex.getCode());
    }

    /**
     * 未知异常
     */
    @ExceptionHandler(Throwable.class)
    public ResponseResult ExceptionHandler(Throwable ex) {
        log.error(" msg : {}", ex.getMessage(), ex);
        if (StringUtils.isBlank(ex.getLocalizedMessage())) {
            return ResponseResult.error(ERROR.getCode(), ERROR.getDesc());
        }
        return ResponseResult.error(ex.getMessage());
    }
}
